<?php 
class ControllerProduct extends Controller {
	var $error = array();
    
  	function index() {
		$response =& $this->locator->get('response');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$module   =& $this->locator->get('module');
			  
		$language->load('controller/product.php');
    	
		$template->set('title', $language->get('heading_title'));
	
    	$template->set('content', $this->getList());
		
		$template->set($module->fetch());
    	
		$response->set($template->fetch('layout.tpl'));
  	}
  
  	function insert() {
    	$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$upload   =& $this->locator->get('upload');
		$url      =& $this->locator->get('url');
		$image    =& $this->locator->get('image');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');
        		 
    	$language->load('controller/product.php');

    	$template->set('title', $language->get('heading_title'));
		
		$image->checkFiles(); //checks for new files in the image folder to ensure they are available
		
    	if ($request->isPost() && $request->has('quantity', 'post') && $this->validateForm()) {
      		
      		// Add image upload to product edit
	  		if ($upload->has('image') && $this->validateUpload() && $upload->save('image', DIR_IMAGE . $upload->getName('image'))) {
				$sql = "insert into image set filename = '?', date_added = now()";
				$database->query($database->parse($sql, $upload->getName('image')));
      		    $image_id = $database->getLastId();
      		    
      		    //Image title forced to image name for all languages
        		foreach ($request->get('name', 'post', array()) as $key => $value) {
        			$sql = "insert into image_description set image_id = '?', language_id = '?', title = '?'";
        			$database->query($database->parse($sql, $image_id, $key, $image->getTitle($upload->getName('image'))));
				}
				$cache->delete('image');
			} else {
				$image_id = $request->gethtml('image_id', 'post');
			}
      		
      		$sql = "insert into product set quantity = '?', date_available = '?', model = '?', manufacturer_id = '?', image_id = '?', shipping = '?', price = '?', sort_order = '?', weight = '?', weight_class_id = '?', status = '?', tax_class_id = '?', min_qty = '?', date_added = now()";
      		$database->query($database->parse($sql, $request->gethtml('quantity', 'post'), date('Y-m-d', strtotime($request->gethtml('date_available_year', 'post').'/'.$request->gethtml('date_available_month', 'post').'/'.$request->gethtml('date_available_day', 'post'))), $request->gethtml('model', 'post'), $request->gethtml('manufacturer_id', 'post'), $image_id, $request->gethtml('shipping', 'post'), $request->gethtml('price', 'post'), $request->gethtml('sort_order', 'post'), $request->gethtml('weight', 'post'), $request->gethtml('weight_class_id', 'post'), $request->gethtml('status', 'post'), $request->gethtml('tax_class_id', 'post'), ($request->gethtml('min_qty', 'post') != null && $request->gethtml('min_qty', 'post') > 0) ? $request->gethtml('min_qty', 'post') : 1));

      		$insert_id = $database->getLastId();

			$name        = $request->get('name', 'post');
			$description = $request->get('description', 'post');
			
      		foreach ($request->get('name', 'post', array()) as $key => $value) {
        		$sql = "insert into product_description set product_id = '?', language_id = '?', name = '?', description = '?'";
                $database->query($database->parse($sql, $insert_id, $key, $name[$key], $description[$key]));
      		}
      		
      		$mkeys = $request->get('meta_keys', 'post');
			$mdescription = $request->get('meta_description', 'post');
			
      		foreach ($request->get('meta_keys', 'post', array()) as $key => $value) {
        		$sql = "insert into product_meta set product_id = '?', language_id = '?', keywords = '?', description = '?'";
                $database->query($database->parse($sql, $insert_id, $key, $mkeys[$key], $mdescription[$key]));
      		}

			foreach ($request->gethtml('product_discount', 'post', array()) as $product_discount) {
				$sql = "insert into product_discount set product_id = '?', quantity = '?', discount = '?'";
				$database->query($database->parse($sql, $insert_id, $product_discount['quantity'], $product_discount['discount']));
			}

      		foreach ($request->gethtml('image', 'post', array()) as $image_id) {
        		$sql = "insert into product_to_image set product_id = '?', image_id = '?'";
        		$database->query($database->parse($sql, $insert_id, $image_id));
      		}
      		
      		foreach (@$request->gethtml('related', 'post', array()) as $related) {
        		if (@$related['id']) {
        			$sql = "insert into product_related set product_id = '?', related_id = '?' ON DUPLICATE KEY UPDATE product_id=product_id";
        			$database->query($database->parse($sql, $insert_id, $related['id'])); //link this product to related
        			if ($related['cross']) {
        				$database->query("delete from product_related where product_id ='".(int)$related['id']."' and related_id = '".(int)$insert_id."'");
        				$database->query($database->parse($sql, $related['id'], $insert_id)); //link related product to this
					}
				}
      		}

      		foreach ($request->gethtml('download', 'post', array()) as $download_id) {
        		$sql = "insert into product_to_download set product_id = '?', download_id = '?'";
        		$database->query($database->parse($sql, $insert_id, $download_id));
      		}
			
      		foreach ($request->gethtml('category', 'post', array()) as $category_id) {
        		$sql = "insert into product_to_category set product_id = '?', category_id = '?'";
        		$database->query($database->parse($sql, $insert_id, $category_id));
	  		}
			
	  		$cache->delete('product');
	  		
			$session->set('message', $language->get('text_message'));
	  
	  		$response->redirect($url->ssl('product'));
    	}
    
    	$template->set('content', $this->getForm());
	
		$template->set($module->fetch());
	
    	$response->set($template->fetch('layout.tpl'));
  	}

  	function update() {
    	$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$upload   =& $this->locator->get('upload');
		$url      =& $this->locator->get('url');
		$image    =& $this->locator->get('image');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');

    	$language->load('controller/product.php');

    	$template->set('title', $language->get('heading_title'));
	
		$image->checkFiles(); //checks for new files in the image folder to ensure they are available
	
    	if ($request->isPost() && $request->has('quantity', 'post') && $this->validateForm()) {
      		      		
      		// Add image upload to product edit
	  		if ($upload->has('image') && $this->validateUpload() && $upload->save('image', DIR_IMAGE . $upload->getName('image'))) {
				$sql = "insert into image set filename = '?', date_added = now()";
				$database->query($database->parse($sql, $upload->getName('image')));
      		    $image_id = $database->getLastId();
      		    
      		    //Image title forced to image name for all languages
        		foreach ($request->get('name', 'post', array()) as $key => $value) {
        			$sql = "insert into image_description set image_id = '?', language_id = '?', title = '?'";
        			$database->query($database->parse($sql, $image_id, $key, $image->getTitle($upload->getName('image'))));
				}
				$cache->delete('image');
			} else {
				$image_id = $request->gethtml('image_id', 'post');
			}
      		
      		$sql = "update product set quantity = '?', date_available = '?', model = '?', manufacturer_id = '?', image_id = '?', shipping = '?', price = '?', sort_order = '?', weight = '?', weight_class_id = '?', status = '?', tax_class_id = '?', min_qty = '?', date_modified = now() where product_id = '?'";
      		$database->query($database->parse($sql, $request->gethtml('quantity', 'post'), date('Y-m-d', strtotime($request->gethtml('date_available_year', 'post').'/'.$request->gethtml('date_available_month', 'post').'/'.$request->gethtml('date_available_day', 'post'))), $request->gethtml('model', 'post'), $request->gethtml('manufacturer_id', 'post'), $image_id, $request->gethtml('shipping', 'post'), $request->gethtml('price', 'post'), $request->gethtml('sort_order', 'post'), $request->gethtml('weight', 'post'), $request->gethtml('weight_class_id', 'post'), $request->gethtml('status', 'post'), $request->gethtml('tax_class_id', 'post'), ($request->gethtml('min_qty', 'post') > 0) ? $request->gethtml('min_qty', 'post') : 1, $request->gethtml('product_id')));
			      		
			$database->query("delete from product_description where product_id = '".(int)$request->gethtml('product_id')."'");

			$name        = $request->get('name', 'post');
			$description = $request->get('description', 'post');
						
		  	foreach ($request->get('name', 'post', array()) as $key => $value) {
        		$sql = "insert into product_description set product_id = '?', language_id = '?', name = '?', description = '?'";
        		$database->query($database->parse($sql, $request->gethtml('product_id'), $key, $value, $description[$key]));
      		}
      		
      		$database->query("delete from product_meta where product_id = '".(int)$request->gethtml('product_id')."'");
      		
      		$mkeys = $request->get('meta_keys', 'post');
			$mdescription = $request->get('meta_description', 'post');
			
      		foreach ($request->get('meta_keys', 'post', array()) as $key => $value) {
        		$sql = "insert into product_meta set product_id = '?', language_id = '?', keywords = '?', description = '?'";
                $database->query($database->parse($sql, $request->gethtml('product_id'), $key, $mkeys[$key], $mdescription[$key]));
      		}

			$database->query("delete from product_discount where product_id = '".(int)$request->gethtml('product_id')."'");

			foreach ($request->gethtml('product_discount', 'post', array()) as $product_discount) {
				$sql = "insert into product_discount set product_id = '?', quantity = '?', discount = '?'";
				$database->query($database->parse($sql, $request->gethtml('product_id'), $product_discount['quantity'], $product_discount['discount']));
			}

			$database->query("delete from product_to_image where product_id = '".(int)$request->gethtml('product_id')."'");

      		foreach ($request->gethtml('image', 'post', array()) as $image_id) {
        		$sql = "insert into product_to_image set product_id = '?', image_id = '?'";
        		$database->query($database->parse($sql, $request->gethtml('product_id'), $image_id));
      		}
      		
      		$database->query("delete from product_related where product_id = '".(int)$request->gethtml('product_id')."'");
			
      		foreach ($request->gethtml('related', 'post', array()) as $related) {
        		if (@$related['id']) {
        			$sql = "insert into product_related set product_id = '?', related_id = '?' ON DUPLICATE KEY UPDATE product_id=product_id";
        			$database->query($database->parse($sql, $request->gethtml('product_id'), $related['id'])); //link this product to related
        			if ($related['cross']) {
        				$database->query("delete from product_related where product_id ='".(int)$related['id']."' and related_id = '".(int)$request->gethtml('product_id')."'");
        				$database->query($database->parse($sql, $related['id'], $request->gethtml('product_id'))); //link related product to this
					}
				}
      		}
			
      		$database->query("delete from product_to_download where product_id = '".(int)$request->gethtml('product_id')."'");

      		foreach ($request->gethtml('download', 'post', array()) as $download_id) {
        		$sql = "insert into product_to_download set product_id = '?', download_id = '?'";
        		$database->query($database->parse($sql, $request->gethtml('product_id'), $download_id));
      		}
	  
      		$database->query("delete from product_to_category where product_id = '".(int)$request->gethtml('product_id')."'");

      		foreach ($request->gethtml('category', 'post', array()) as $category_id) { 
        		$sql = "insert into product_to_category set product_id = '?', category_id = '?'";
        		$database->query($database->parse($sql, $request->gethtml('product_id'), $category_id));
      		}
      
	  		$cache->delete('product');
	  		 		
			$session->set('message', $language->get('text_message'));
	  		
			$response->redirect($url->ssl('product'));
		}
    
    	$template->set('content', $this->getForm());
	
		$template->set($module->fetch());
	
    	$response->set($template->fetch('layout.tpl'));
  	}

  	function delete() {
    	$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');

    	$language->load('controller/product.php');

    	$template->set('title', $language->get('heading_title'));
	
    	if (($request->gethtml('product_id')) && ($this->validateDelete())) {
      		$database->query("delete from product where product_id = '".(int)$request->gethtml('product_id')."'");
      		$database->query("delete from product_description where product_id = '".(int)$request->gethtml('product_id')."'");
      		$database->query("delete from product_to_option where product_id = '".(int)$request->gethtml('product_id')."'");
      		$database->query("delete from product_to_image where product_id = '".(int)$request->gethtml('product_id')."'");
	  		$database->query("delete from product_to_download where product_id = '".(int)$request->gethtml('product_id')."'");
      		$database->query("delete from product_to_category where product_id = '".(int)$request->gethtml('product_id')."'");
	  		$database->query("delete from review where product_id = '".(int)$request->gethtml('product_id')."'");
      
	  		$cache->delete('product');
	  		
			$session->set('message', $language->get('text_message'));
	  
	  		$response->redirect($url->ssl('product'));
    	}
    
    	$template->set('content', $this->getList());
	
		$template->set($module->fetch());
	
    	$response->set($template->fetch('layout.tpl'));
  	}
  	
  	function listAction() {
    	$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');

    	$language->load('controller/product.php');

    	$template->set('title', $language->get('heading_title'));
	
    	if (($request->has('listitem', 'post')) && ($this->validateAction())) {
      		foreach ($request->gethtml('listitem', 'post') as $product_id) {
      			if ($request->gethtml('listcmd', 'post') == $language->get('select_delete')) {
      				$database->query("delete from product where product_id = '".$product_id."'");
      				$database->query("delete from product_description where product_id = '".$product_id."'");
      				$database->query("delete from product_to_option where product_id = '".$product_id."'");
      				$database->query("delete from product_to_image where product_id = '".$product_id."'");
	  				$database->query("delete from product_to_download where product_id = '".$product_id."'");
      				$database->query("delete from product_to_category where product_id = '".$product_id."'");
	  				$database->query("delete from review where product_id = '".$product_id."'");
	  				$session->set('message', $language->get('text_delete_message'));
				} elseif ($request->gethtml('listcmd', 'post') == $language->get('select_toggle')) { 
					$result = $database->getRow("select status from product where `product_id` = '" . $product_id . "'"); 
					$sql = "update product set status = '?' where product_id = '?'";
      				$database->query($database->parse($sql, ($result['status'] == 1) ? 0 : 1, $product_id));
					$session->set('message', $language->get('text_status_message'));
				} elseif ($request->gethtml('listcmd', 'post') == $language->get('select_clone')) { 
					// Clone product table
		            $row = $database->getRow("select * from product where `product_id` = '" . $product_id . "'");
		            $row['product_id'] = NULL;
		            $result = $database->query("insert into product (" . implode(", ", array_keys($row)). ") VALUES ('" . implode("', '", array_values($row)) . "')");
		            
		            // Get new product_id
		            $insert_id = $database->getLastId();
		            
		            // Clone product_description table for each language
		            $rows = $database->getRows("select * from product_description where `product_id` = '" . $product_id . "'");
		            foreach ($rows as $row) {
		                $row['product_id'] = $insert_id;
		                $i = $database->countRows("select name from `product_description` where `name` LIKE '" . addslashes($row['name']) . "%'");
		                $row['name'] = addslashes($row['name']) . $language->get('text_clone_sfx', $i);
		                $row['description'] = addslashes($row['description']);
		                $result = $database->query("insert into product_description (" . implode(", ", array_keys($row)). ") VALUES ('" . implode("', '", array_values($row)) . "')");
		            }
		            
		            // Clone product_discount table for each discount
		            $rows = $database->getRows("select * from product_discount where `product_id` = '" . $product_id . "'");
		            foreach ($rows as $row) {
		                $row['product_discount_id'] = NULL;
		                $row['product_id'] = $insert_id;
		                $result = $database->query("insert into product_discount (" . implode(", ", array_keys($row)). ") VALUES ('" . implode("', '", array_values($row)) . "')");
		            }
		            
		            // Clone product_to_option table for each option
		            $rows = $database->getRows("select * from product_to_option where `product_id` = '" . $product_id . "'");
		            foreach ($rows as $row) {
		                $row['product_to_option_id'] = NULL;
		                $row['product_id'] = $insert_id;
		                $result = $database->query("insert into product_to_option (" . implode(", ", array_keys($row)). ") VALUES ('" . implode("', '", array_values($row)) . "')");
		            }
		            
		            // Clone product_to_image table for each image
		            $rows = $database->getRows("select * from product_to_image where `product_id` = '" . $product_id . "'");
		            foreach ($rows as $row) {
		                $row['product_id'] = $insert_id;
		                $result = $database->query("insert into product_to_image (" . implode(", ", array_keys($row)). ") VALUES ('" . implode("', '", array_values($row)) . "')");
		            }
		            
		            // Clone product_to_download table for each download
		            $rows = $database->getRows("select * from product_to_download where `product_id` = '" . $product_id . "'");
		            foreach ($rows as $row) {
		                $row['product_id'] = $insert_id;
		                $result = $database->query("insert into product_to_download (" . implode(", ", array_keys($row)). ") VALUES ('" . implode("', '", array_values($row)) . "')");
		            }
		            
		            // Clone product_to_category table for each category
		            $rows = $database->getRows("select * from product_to_category where `product_id` = '" . $product_id . "'");
		            foreach ($rows as $row) {
		                $row['product_id'] = $insert_id;
		                $result = $database->query("insert into product_to_category (" . implode(", ", array_keys($row)). ") VALUES ('" . implode("', '", array_values($row)) . "')");
		            }
		            
		            $session->set('message', $language->get('text_clone_message'));
				}
			}
	  		$cache->delete('product');
	  		
	  		$response->redirect($url->ssl('product'));
    	}
    
    	$template->set('content', $this->getList());
	
		$template->set($module->fetch());
	
    	$response->set($template->fetch('layout.tpl'));
  	}

  	function getList() {
    	$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$config   =& $this->locator->get('config');
		$image	  =& $this->locator->get('image');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$session  =& $this->locator->get('session');
		$template =& $this->locator->get('template');

    	$cols = array();
    	
    	$cols[] = array(
        	'name'  => $language->get('column_id'),
        	'sort'  => 'p.product_id',
			'href'  => $url->ssl('product', 'page', array('sort' => 'p.product_id', 'order' => ($request->gethtml('order') == 'desc') ? 'asc' : 'desc')),
        	'align' => 'left'
        );
    	
    	$cols[] = array(
      		'name'  => $language->get('column_name'),
      		'sort'  => 'pd.name',
      		'href'  => $url->ssl('product', 'page', array('sort' => 'pd.name', 'order' => ($request->gethtml('order') == 'desc') ? 'asc' : 'desc')),
      		'align' => 'left'
    	);
		
    	$cols[] = array(
      		'name'  => $language->get('column_model'),
      		'sort'  => 'p.model',
      		'href'  => $url->ssl('product', 'page', array('sort' => 'p.model', 'order' => ($request->gethtml('order') == 'desc') ? 'asc' : 'desc')),
      		'align' => 'left'
    	);
    	
    	$cols[] = array(
      		'name'  => $language->get('column_price'),
      		'sort'  => 'p.price',
      		'href'  => $url->ssl('product', 'page', array('sort' => 'p.price', 'order' => ($request->gethtml('order') == 'desc') ? 'asc' : 'desc')),
      		'align' => 'left'
    	);
    	
    	$cols[] = array(
      		'name'  => $language->get('column_weight'),
      		'sort'  => 'p.weight',
      		'href'  => $url->ssl('product', 'page', array('sort' => 'p.weight', 'order' => ($request->gethtml('order') == 'desc') ? 'asc' : 'desc')),
      		'align' => 'left'
    	);
    	
    	$cols[] = array(
      		'name'  => $language->get('column_quantity'),
      		'sort'  => 'p.quantity',
      		'href'  => $url->ssl('product', 'page', array('sort' => 'p.quantity', 'order' => ($request->gethtml('order') == 'desc') ? 'asc' : 'desc')),
      		'align' => 'center'
    	);
    				
    	$cols[] = array(
      		'name'  => $language->get('column_sort_order'),
      		'align' => 'center'
    	);
    	
    	$cols[] = array(
      		'name'  => $language->get('column_image'),
      		'align' => 'right'
    	);
    	
    	$cols[] = array(
      		'name'  => $language->get('column_action'),
      		'align' => 'right'
    	);
    	
    	$cols[] = array(
        	'name' => '<input type="checkbox" name="checkall" onclick="$(\'input[name*=listitem]\').attr(\'checked\', this.checked);" />',
            'align' => 'right'
        );
								
    	if (!$session->get('product.search')) {
      		$sql = "select * from product p left join product_description pd on (p.product_id = pd.product_id) where pd.language_id = '".(int)$language->getId()."'";
    	} else {
      		$sql = "select * from product p left join product_description pd on (p.product_id = pd.product_id) where pd.language_id = '".(int)$language->getId()."' and pd.name like '?'";
    	}
    
		$sort = array(
	  		'p.product_id',
	  		'pd.name', 
			'p.model',
			'p.price',
			'p.weight',
			'p.quantity',
	  		'p.sort_order', 
	  		'p.status'
		);
	
    	if (in_array($session->get('product.sort'), $sort)) {
      		$sql .= " order by ".$session->get('product.sort')." ".(($session->get('product.order') == 'desc') ? 'desc' : 'asc');
    	} else {
      		$sql .= " order by pd.name asc";
    	}
    
    	$results = $database->getRows($database->splitQuery($database->parse($sql, '%'.$session->get('product.search').'%'), $session->get('product.page'), $config->get('config_max_rows')));

    	$rows = array();

    	foreach ($results as $result) {
      		$cell = array();      		
        	
        	$cell[] = array(
            	'value' => $result['product_id'],
            	'align' => 'left'
        	);
			
      		$cell[] = array(
        		'value' => $result['name'],
        		'align' => 'left'
		  	);

      		$cell[] = array(
        		'value' => $result['model'],
        		'align' => 'left'
      		);
      		
      		$cell[] = array(
        		'value' => $result['price'],
        		'align' => 'left'
      		);
      		
      		$cell[] = array(
        		'value' => $result['weight'],
        		'align' => 'left'
      		);
      		
      		$cell[] = array(
        		'value' => $result['quantity'],
        		'align' => 'center'
      		);
      		
      		$cell[] = array(
        		'value' => $result['sort_order'],
        		'align' => 'center'
      		);
      		
      		$img = $database->getRow("select filename from image where image_id = '".$result['image_id']."'");
			$cell[] = array(
				'image' => $image->resize($img['filename'], '22', '22'),
				'align' => 'right'
			);
			
			$action = array();
      		
			$action[] = array(
        		'icon' => 'update.png',
				'text' => $language->get('button_update'),
				'href' => $url->ssl('product', 'update', array('product_id' => $result['product_id']))
      		);
      		
      		$action[] = array(
        		'icon' => 'folder.png',
				'text' => $language->get('button_options'),
				'href' => $url->ssl('product_option', FALSE, array('product_id' => $result['product_id']))
      		);
      		
      		$action[] = array(
        		'icon' => ($result['status'] ? 'enabled.png' : 'disabled.png'),
				'text' => $language->get('button_status'),
				'href' => $url->ssl('product', 'toggleStatus', array('product_id' => $result['product_id']))
      		);

      		$action[] = array(
        		'icon' => 'delete.png',
				'text' => $language->get('button_delete'),
				'href' => $url->ssl('product', 'delete', array('product_id' => $result['product_id']))
      		);
      		
      		$cell[] = array(
        		'action' => $action,
        		'align'  => 'right'
      		);
			
			$cell[] = array(
            	'value' => '<input type="checkbox" name="listitem[]" value="' . $result['product_id'] . '" />',
            	'align' => 'right'
        	);
			
			$rows[] = array('cell' => $cell);
    	}

    	$view = $this->locator->create('template');

		$view->set('tpl', $template);

    	$view->set('heading_title', $language->get('heading_title'));
    	$view->set('heading_description', $language->get('heading_description'));

    	$view->set('text_results', $language->get('text_results', $database->getFrom(), $database->getTo(), $database->getTotal()));
		$view->set('select_clone', $language->get('select_clone'));
		$view->set('select_toggle', $language->get('select_toggle'));
		$view->set('select_delete', $language->get('select_delete'));
		
    	$view->set('entry_page', $language->get('entry_page'));
    	$view->set('entry_search', $language->get('entry_search'));
    	
    	
    	$view->set('button_insert', $language->get('button_insert'));
    	$view->set('button_update', $language->get('button_update'));
   	 	$view->set('button_delete', $language->get('button_delete'));
    	$view->set('button_cancel', $language->get('button_cancel'));
    	$view->set('button_options', $language->get('button_options'));
    	$view->set('button_status', $language->get('button_status'));

    	$view->set('error', @$this->error['message']);
 
 		$view->set('message', $session->get('message'));
		
		$session->delete('message');
		
		$view->set('listaction', $url->ssl('product', 'listAction'));
		
		$view->set('colspan', count($cols));
		
		$view->set('selectbox', array($language->get('select_clone'), $language->get('select_toggle'), $language->get('select_delete')));//Q
		 
    	$view->set('action', $url->ssl('product', 'page'));

    	$view->set('search', $session->get('product.search'));
		$session->delete('product.search');
    	$view->set('sort', $session->get('product.sort'));
    	$view->set('order', $session->get('product.order'));
    	
    	$view->set('page', $session->get('product.page'));
 
    	$view->set('cols', $cols);
    	$view->set('rows', $rows);
    
    	$view->set('insert', $url->ssl('product', 'insert'));
  
    	$page_data = array();

    	for ($i = 1; $i <= $database->getPages(); $i++) {
      		$page_data[] = array(
        		'text'  => $language->get('text_pages', $i, $database->getPages()),
        		'value' => $i
      		); 
    	} 

    	$view->set('pages', $page_data);

		return $view->fetch('content/list.tpl');
  	}

  	function getForm() {
		$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$config   =& $this->locator->get('config');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
   
    	$view = $this->locator->create('template');

		$view->set('tpl', $template);

    	$view->set('heading_title', $language->get('heading_title'));
    	$view->set('heading_description', $language->get('heading_description'));

    	$view->set('text_enabled', $language->get('text_enabled'));
    	$view->set('text_disabled', $language->get('text_disabled'));
    	$view->set('text_none', $language->get('text_none'));
    	$view->set('text_yes', $language->get('text_yes'));
    	$view->set('text_no', $language->get('text_no'));
 		$view->set('text_plus', $language->get('text_plus'));
		$view->set('text_minus', $language->get('text_minus'));
		$view->set('text_or', $language->get('text_or'));
		$view->set('text_related_cross', $language->get('text_related_cross'));
		
    	$view->set('entry_name', $language->get('entry_name'));
    	$view->set('entry_description', $language->get('entry_description'));
    	$view->set('entry_model', $language->get('entry_model'));
		$view->set('entry_manufacturer', $language->get('entry_manufacturer'));
    	$view->set('entry_shipping', $language->get('entry_shipping'));
    	$view->set('entry_date_available', $language->get('entry_date_available'));
    	$view->set('entry_quantity', $language->get('entry_quantity'));
		$view->set('entry_discount', $language->get('entry_discount'));
    	$view->set('entry_status', $language->get('entry_status'));
    	$view->set('entry_sort_order', $language->get('entry_sort_order'));
    	$view->set('entry_tax_class', $language->get('entry_tax_class'));
    	$view->set('entry_price', $language->get('entry_price'));
    	$view->set('entry_weight_class', $language->get('entry_weight_class'));
    	$view->set('entry_weight', $language->get('entry_weight'));
		$view->set('entry_prefix', $language->get('entry_prefix'));
    	$view->set('entry_image', $language->get('entry_image'));
    	$view->set('entry_images', $language->get('entry_images'));
    	$view->set('entry_download', $language->get('entry_download'));
    	$view->set('entry_category', $language->get('entry_category'));
        $view->set('entry_min_qty', $language->get('entry_min_qty'));
		$view->set('entry_upload', $language->get('entry_upload'));
		$view->set('entry_meta_keys', $language->get('entry_meta_keys'));
		$view->set('entry_meta_description', $language->get('entry_meta_description'));
		$view->set('entry_related', $language->get('entry_related'));
        
    	$view->set('button_save', $language->get('button_save'));
    	$view->set('button_cancel', $language->get('button_cancel'));
		$view->set('button_add', $language->get('button_add'));
		$view->set('button_remove', $language->get('button_remove'));
		
    	$view->set('tab_general', $language->get('tab_general'));
    	$view->set('tab_data', $language->get('tab_data'));
		$view->set('tab_discount', $language->get('tab_discount'));
    	$view->set('tab_image', $language->get('tab_image'));
    	$view->set('tab_download', $language->get('tab_download'));
    	$view->set('tab_category', $language->get('tab_category'));
		$view->set('tab_meta', $language->get('tab_meta'));

    	$view->set('error', @$this->error['message']);
    	$view->set('error_upload', @$this->error['upload']);
    	$view->set('error_name', @$this->error['name']);
    	$view->set('error_description', @$this->error['description']);
    	$view->set('error_model', @$this->error['model']);
    	$view->set('error_date_available', @$this->error['date_available']);
		
    	$view->set('action', $url->ssl('product', $request->gethtml('action'), array('product_id' => $request->gethtml('product_id'))));
  
    	$view->set('cancel', $url->ssl('product'));

		// Language query
		$results = $database->cache('language', "select * from language order by sort_order");
    	
    	// Product Name & Description
    	$product_data = array();
    
    	foreach ($results as $result) {
			if (($request->gethtml('product_id')) && (!$request->isPost())) {
	  			$product_description_info = $database->getRow("select name, description from product_description where product_id = '".(int)$request->gethtml('product_id')."' and language_id = '".(int)$result['language_id']."'");
			}
			
			$name        = $request->gethtml('name', 'post');
			$description = $request->get('description', 'post');
	  		
			$product_data[] = array(
	    		'language_id' => $result['language_id'],
	    		'language'    => $result['name'],
	    		'name'        => (isset($name[$result['language_id']]) ? $name[$result['language_id']] : @htmlspecialchars($product_description_info['name'])),
	    		'description' => (isset($description[$result['language_id']])?$description[$result['language_id']]:@$product_description_info['description'])
	  		);
    	}

    	$view->set('products', $product_data);
    	
    	
    	// Meta Keywords & Description
    	foreach ($results as $result) {
			if (($request->gethtml('product_id')) && (!$request->isPost())) {
	  			$product_meta_info = $database->getRow("select keywords, description from product_meta where product_id = '".(int)$request->gethtml('product_id')."' and language_id = '".(int)$result['language_id']."'");
			}
			
			$meta_keys        = $request->gethtml('meta_keys', 'post');
			$meta_description = $request->get('meta_description', 'post');
	  		
			$products_meta[] = array(
	    		'language_id' => $result['language_id'],
	    		'language'    => $result['name'],
	    		'meta_keys'        => (isset($meta_keys[$result['language_id']]) ? $meta_keys[$result['language_id']] : @htmlspecialchars($product_meta_info['keywords'])),
	    		'meta_description' => (isset($meta_description[$result['language_id']])?$meta_description[$result['language_id']]:@$product_meta_info['description'])
	  		);
    	}

    	$view->set('products_meta', $products_meta);

    	
    	if (($request->gethtml('product_id')) && (!$request->isPost())) {
      		$product_info = $database->getRow("select distinct * from product where product_id = '".(int)$request->gethtml('product_id')."'");
    	}

    	if ($request->has('model', 'post')) {
      		$view->set('model', $request->gethtml('model', 'post'));
    	} else {
      		$view->set('model', @$product_info['model']);
    	}

    	$view->set('manufacturers', $database->cache('manufacturer', "select * from manufacturer order by sort_order, name asc"));

    	if ($request->has('manufacturer_id', 'post')) {
      		$view->set('manufacturer_id', $request->gethtml('manufacturer_id', 'post'));
    	} else {
      		$view->set('manufacturer_id', @$product_info['manufacturer_id']);
    	} 
		
    	if ($request->has('shipping', 'post')) {
      		$view->set('shipping', $request->gethtml('shipping', 'post'));
    	} elseif (isset($product_info['shipping'])) {
    		$view->set('shipping', @$product_info['shipping']);
    	} else {
      		$view->set('shipping', '1');
    	}
  
    	if ($request->has('image_id', 'post')) {
      		$view->set('image_id', $request->gethtml('image_id', 'post'));
    	} else {
      		$view->set('image_id', @$product_info['image_id']);
    	}

    	$month_data = array();

    	$month_data[] = array(
      		'value' => '01',
      		'text'  => $language->get('text_january')
    	);

    	$month_data[] = array(
      		'value' => '02',
      		'text'  => $language->get('text_february')
    	);

    	$month_data[] = array(
      		'value' => '03',
      		'text'  => $language->get('text_march')
    	);

    	$month_data[] = array(
      		'value' => '04',
      		'text'  => $language->get('text_april')
    	);

    	$month_data[] = array(
      		'value' => '05',
      		'text'  => $language->get('text_may')
    	);

    	$month_data[] = array(
      		'value' => '06',
      		'text'  => $language->get('text_june')
    	);

    	$month_data[] = array(
      		'value' => '07',
      		'text'  => $language->get('text_july')
    	);

    	$month_data[] = array(
      		'value' => '08',
      		'text'  => $language->get('text_august')
    	);

    	$month_data[] = array(
      		'value' => '09',
      		'text'  => $language->get('text_september')
    	);

    	$month_data[] = array(
      		'value' => '10',
      		'text'  => $language->get('text_october')
    	);

    	$month_data[] = array(
      		'value' => '11',
      		'text'  => $language->get('text_november')
    	);

    	$month_data[] = array(
      		'value' => '12',
      		'text'  => $language->get('text_december')
    	);

    	$view->set('months', $month_data);
      	
		if (isset($product_info['date_available'])) {
        	$date = explode('/', date('d/m/Y', strtotime($product_info['date_available'])));
      	} else {
        	$date = explode('/', date('d/m/Y', time()));
      	}
			
    	if ($request->has('date_available_day', 'post')) {
      		$view->set('date_available_day', $request->gethtml('date_available_day', 'post'));
    	} else {
      		$view->set('date_available_day', $date[0]);
    	}			
			
    	if ($request->has('date_available_month', 'post')) {
      		$view->set('date_available_month', $request->gethtml('date_available_month', 'post'));
    	} else {
      		$view->set('date_available_month', $date[1]);
    	}

    	if ($request->has('date_available_year', 'post')) {
      		$view->set('date_available_year', $request->gethtml('date_available_year', 'post'));
    	} else {
      		$view->set('date_available_year', $date[2]);
    	}					
			
    	if ($request->has('quantity', 'post')) {
      		$view->set('quantity', $request->gethtml('quantity', 'post'));
    	} elseif (isset($product_info['quantity'])) {
      		$view->set('quantity', @$product_info['quantity']);
    	} else {
            $view->set('quantity', 1);
        }

        if ( $request->has('min_qty', 'post')) {
            $view->set('min_qty', $request->gethtml('min_qty', 'post'));
        } elseif (isset($product_info['min_qty'])) {
            $view->set('min_qty', @$product_info['min_qty']);
        } else {
            $view->set('min_qty', 1);
        }
    	
    	if ($request->has('price', 'post')) {
      		$view->set('price', $request->gethtml('price', 'post'));
    	} else {
      		$view->set('price', @$product_info['price']);
    	}
  
    	if ($request->has('sort_order', 'post')) {
      		$view->set('sort_order', $request->gethtml('sort_order', 'post'));
    	} else {
      		$view->set('sort_order', @$product_info['sort_order']);
    	}

    	if ($request->has('status', 'post')) {
      		$view->set('status', $request->gethtml('status', 'post'));
    	} elseif (isset($product_info['status'])) {
    		$view->set('status', @$product_info['status']);
    	} else {
      		$view->set('status', '1');
    	}

    	if ($request->has('tax_class_id', 'post')) {
      		$view->set('tax_class_id', $request->gethtml('tax_class_id', 'post'));
    	} else {
      		$view->set('tax_class_id', @$product_info['tax_class_id']);
    	}

    	$view->set('tax_classes', $database->cache('tax_class', "select * from tax_class"));

    	if ($request->has('weight', 'post')) {
      		$view->set('weight', $request->gethtml('weight', 'post'));
    	} else {
      		$view->set('weight', @$product_info['weight']);
    	} 

    	if ($request->has('weight_class_id', 'post')) {
      		$view->set('weight_class_id', $request->gethtml('weight_class_id', 'post'));
    	} elseif (isset($product_info['weight_class_id'])) {
      		$view->set('weight_class_id', @$product_info['weight_class_id']);
    	} else {
      		$view->set('weight_class_id', $config->get('config_weight_class_id'));
    	}

    	$view->set('weight_classes', $database->cache('weight_class-'.$language->getId(), "select weight_class_id, title from weight_class where language_id = '".(int)$language->getId()."'"));

     	$product_discount_data = array();
		
		if (!$request->has('product_discount', 'post')) {
    		$results = $database->getRows("select product_discount_id, quantity, discount from product_discount where product_id = '".(int)$request->gethtml('product_id')."'");

    		foreach ($results as $result) {
      			$product_discount_data[] = array(
        			'quantity' => $result['quantity'],
					'discount' => $result['discount']
      			);
    		}
  		
			$view->set('product_discounts', $product_discount_data);
		} else {
			$view->set('product_discounts', $request->gethtml('product_discount', 'post', array()));
		}
		
		
		// Images
    	$image_data = array();

    	$results = $database->cache('image', "select i.image_id, i.filename, id.title from image i left join image_description id on (i.image_id = id.image_id) where id.language_id = '".(int)$language->getId()."' order by i.image_id");

    	foreach ($results as $result) {
			if (($request->gethtml('product_id')) && (!$request->isPost())) {  
	  			$product_to_image_info = $database->getRow("select * from product_to_image where product_id = '".(int)$request->gethtml('product_id')."' and image_id = '".(int)$result['image_id']."'");
			}

      		$image_data[] = array(
        		'image_id'   => $result['image_id'],
        		'title'      => $result['title'],
        		'product_id' => (isset($product_to_image_info) ? $product_to_image_info : in_array($result['image_id'], $request->gethtml('image', 'post', array())))
      		);
    	}
    	
    	$view->set('images', $image_data);

    	
    	//Related Products
    	$related = array();

    	$results = $database->getRows("select p.product_id as product_id, name from product p left join product_description pd on (p.product_id = pd.product_id) where pd.language_id = '".(int)$language->getId()."' and p.product_id <> '".(int)$request->gethtml('product_id')."'");

    	foreach ($results as $result) {
			if (($request->gethtml('product_id')) && (!$request->isPost())) {  
	  			$product_related_info = $database->getRow("select * from product_related where product_id = '".(int)$request->gethtml('product_id')."' and related_id = '".(int)$result['product_id']."'");
			}

      		$related_data[] = array(
        		'related_id' => $result['product_id'],
        		'title'      => $result['name'],
        		'product_id' => (isset($product_related_info) ? $product_related_info : in_array($result['product_id'], $request->gethtml('related', 'post', array()))),
      		);
    	}
    	
    	$view->set('related', $related_data);
    	
    	
    	// Downloads
    	$download_data = array();

    	$results = $database->getRows("select d.download_id, d.filename, dd.name from download d left join download_description dd on d.download_id = dd.download_id where dd.language_id = '".(int)$language->getId()."' order by dd.name");

    	foreach ($results as $result) {
			if (($request->gethtml('product_id')) && (!$request->isPost())) {
	  			$product_to_download_info = $database->getRow("select * from product_to_download where product_id = '".(int)$request->gethtml('product_id')."' and download_id = '".(int)$result['download_id']."'");
			}
			
      		$download_data[] = array(
        		'download_id' => $result['download_id'],
        		'name'        => $result['name'],
        		'product_id'  => (isset($product_to_download_info) ? $product_to_download_info : in_array($result['download_id'], $request->gethtml('download', 'post', array())))
      		);
    	}

    	$view->set('downloads', $download_data);
	
    	$category_data = array();
   
    	$results = $database->getRows("select c.category_id, cd.name, c.parent_id, c.path from category c left join category_description cd on (c.category_id = cd.category_id) where cd.language_id = '".(int)$language->getId()."' order by c.path");

    	foreach ($results as $result) {
			if (($request->gethtml('product_id')) && (!$request->isPost())) {
	  			$product_to_category_info = $database->getRow("select * from product_to_category where product_id = '".(int)$request->gethtml('product_id')."' and category_id = '".(int)$result['category_id']."'");
			} 		
      		
			$category_data[] = array(
        		'category_id' => $result['category_id'],
        		'name'        => str_repeat('&nbsp;&nbsp;&nbsp;', count(explode('_', $result['path'])) - 1).$result['name'],
        		'product_id'  => (isset($product_to_category_info) ? $product_to_category_info : in_array($result['category_id'], $request->gethtml('category', 'post', array())))
      		);
    	}
 
    	$view->set('categories', $category_data);

		$editor = $this->locator->create('template');
		$view->set('editor',$editor->fetch('content/editor.tpl'));

 		return $view->fetch('content/product.tpl');
  	}
	
  	function validateForm() {
		$request  =& $this->locator->get('request');
		$language =& $this->locator->get('language');
		$user     =& $this->locator->get('user');
        $validate =& $this->locator->get('validate');

    	if (!$user->hasPermission('modify', 'product')) {
      		$this->error['message'] = $language->get('error_permission');
    	}
	      
    	foreach ($request->get('name', 'post', array()) as $value) {
            if (!$validate->strlen($value,1,255)) {
                $this->error['name'] = $language->get('error_name');
            }
    	}

		if (!$request->gethtml('date_available_month', 'post') || !$request->gethtml('date_available_day', 'post') || !$request->gethtml('date_available_year', 'post')) {
	  		$this->error['date_available'] = $language->get('error_date_available');
		}
    	elseif (!checkdate($request->gethtml('date_available_month', 'post'), $request->gethtml('date_available_day', 'post'), $request->gethtml('date_available_year', 'post'))) {
	  		$this->error['date_available'] = $language->get('error_date_available');
		}

		if (!$this->validateUpload()) {
			return FALSE;
		}
		
    	if (!$this->error) {
      		return TRUE;
    	} else {
      		return FALSE;
    	}
  	}

  	function validateAction() {
		$language =& $this->locator->get('language');
		$user     =& $this->locator->get('user');  
    
    	if (!$user->hasPermission('modify', 'product')) {
      		$this->error['message'] = $language->get('error_permission');  
    	}
	  	
		if (!$this->error) {
	  		return TRUE;
		} else {
	  		return FALSE;
		}
  	}
  	
  	function validateUpload() {
		$allowed = array(
			'image/jpeg',
			'image/pjpeg',
			'image/gif', 
			'image/png',
			'image/x-png'
		);

		$request  =& $this->locator->get('request');
		$language =& $this->locator->get('language');
		$user     =& $this->locator->get('user');
		$upload   =& $this->locator->get('upload');
        $validate =& $this->locator->get('validate');
        $image    =& $this->locator->get('image');

		if ($upload->has('image'))  {

	  		if ($upload->hasError('image')) {
	    		$this->error['upload'] = $language->get('error_upload');
	  		}

	  		if (!$validate->strlen($upload->getName('image'),1,128)) {
        		$this->error['upload'] = $language->get('error_filename');
			}
      
	    	if (!in_array($upload->getType('image'), $allowed)) {
          		$this->error['upload'] = $language->get('error_filetype');
        	}
	  
			if ($upload->hasError('image')) {
				$this->error['message'] = $upload->getError('image');
			}
    	}
		
		if (!$this->error) {
	  		return TRUE;
		}
  	}
  	
  	function validateDelete() {
		$language =& $this->locator->get('language');
		$user     =& $this->locator->get('user');  
    
    	if (!$user->hasPermission('modify', 'product')) {
      		$this->error['message'] = $language->get('error_permission');  
    	}
	  	
		if (!$this->error) {
	  		return TRUE;
		} else {
	  		return FALSE;
		}
  	}
	
  	function page() {
    	$request  =& $this->locator->get('request');
    	$response =& $this->locator->get('response');
		$url      =& $this->locator->get('url');
    	$session  =& $this->locator->get('session');	
	
		$session->delete('product.search');
		
		if ($request->has('search', 'post') && $request->gethtml('search', 'post') != '') {
	  		$session->set('product.search', $request->gethtml('search', 'post'));
		}
	 
		if (($request->has('page', 'post')) || ($request->has('search', 'post'))) {
	  		$session->set('product.page', $request->gethtml('page', 'post'));
		} 
	
		if ($request->has('order')) {
	  		$session->set('product.order', (($session->get('product.sort') == $request->gethtml('sort')) && ($session->get('product.order') == 'asc') ? 'desc' : 'asc'));
		}
		
		if ($request->has('sort')) {
			$session->set('product.sort', $request->gethtml('sort'));
		}
				
		$response->redirect($url->ssl('product'));
  	} 	

	function discount() {
		$database =& $this->locator->get('database');
		$language =& $this->locator->get('language');
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		
		$language->load('controller/product.php');
			
		$view = $this->locator->create('template');
	
		$view->set('entry_quantity', $language->get('entry_quantity'));
		$view->set('entry_discount', $language->get('entry_discount'));

		$view->set('button_add', $language->get('button_add'));
		$view->set('button_remove', $language->get('button_remove'));
						
		$option_data = array();

		$view->set('discount_id', $request->gethtml('discount_id'));
		
		$response->set($view->fetch('content/product_discount.tpl'));
	}
	
	function toggleStatus() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');
		
		$language->load('controller/product.php');
		
		$result = $database->getRow("select status from product where `product_id` = '" . $request->gethtml('product_id') . "'"); 
		$sql = "update product set status = '?' where product_id = '?'";
      	$database->query($database->parse($sql, ($result['status'] == 1) ? 0 : 1, $request->gethtml('product_id')));
		
		$cache->delete('product');
	  		
		$session->set('message', $language->get('text_status_message'));
		$response->redirect($url->ssl('product'));     		
		
	}
	
}
?>
